// 提取科目名称
const subjects = Object.keys(data[0]).filter(key => /[语数道理历生化政]/.test(key));
// const subjects = Object.keys(data[0]).filter(key => /[语数物化]/.test(key)); //九年级省模拟考
// const subjects = Object.keys(data[0]).filter(key => key !== '年级' && key !== '班级' && key !== '考号' && key !== '姓名');

// 提取班级列表并排序
const classes = [...new Set(data.map(item => item.班级))].sort((a, b) => a - b);

// 计算考试人数情况
const examAttendance = document.getElementById('examAttendance');

// 获取总人数
const totalStudents = data.length;

// 任务：计算各班参加考试的人数
const classAttendance = classes.map(cls => {
    const total = data.filter(item => item.班级 === cls).length;
    const attendedSubjects = subjects.map(subject => {
        return data.filter(item => item.班级 === cls && item[subject] !== 0).length;
    });
    return { class: cls, total, attendedSubjects };
});

// 渲染考试人数情况为表格
examAttendance.innerHTML = `
    <div class="col-md-12">
        <table class="table table-bordered">
            <thead>
                <tr>
                    <th scope="col">班级</th>
                    <th scope="col">应考人数</th>
                    ${subjects.map(subject => `<th scope="col">${subject}</th>`).join('')}
                </tr>
            </thead>
            <tbody>
                <tr>
                    <td>总计</td>
                    <td>${totalStudents}</td>
                    ${subjects.map(subject => `<td>${data.filter(item => item[subject] !== 0).length}</td>`).join('')}
                </tr>
                ${classAttendance.map(item => `
                    <tr>
                        <td>${item.class} 班</td>
                        <td>${item.total}</td>
                        ${item.attendedSubjects.map(count => `<td>${count}</td>`).join('')}
                    </tr>
                `).join('')}
            </tbody>
        </table>
    </div>
`;


// 任务：计算考试人数缺考情况
const examNotAttendance = document.getElementById('examNotAttendance');
const classNotAttendance = classes.map(cls => {
    const classData = data.filter(item => item.班级 === cls);
    const total = classData.length;
    const notAttendedSubjects = subjects.map(subject => {
        return classData.filter(item => item[subject] === 0).length;
    });
    return { class: cls, total, notAttendedSubjects };
});

// 计算总计行
const totalNotAttendedSubjects = subjects.map(subject => {
    return data.filter(item => item[subject] === 0).length;
});

// 渲染考试人数缺考情况为表格，包含总计行
examNotAttendance.innerHTML = `
    <div class="col-md-12">
        <table class="table table-bordered">
            <thead>
                <tr>
                    <th scope="col">班级</th>
                    <th scope="col">应考人数</th>
                    ${subjects.map(subject => `<th scope="col">${subject}缺考数</th>`).join('')}
                </tr>
            </thead>
            <tbody>
                <!-- 总计行 -->
                <tr>
                    <td>总计</td>
                    <td>${totalStudents}</td>
                    ${totalNotAttendedSubjects.map(count => `<td>${count}</td>`).join('')}
                </tr>
                <!-- 各班数据 -->
                ${classNotAttendance.map(item => `
                    <tr>
                        <td>${item.class} 班</td>
                        <td>${item.total}</td>
                        ${item.notAttendedSubjects.map(count => `<td>${count}</td>`).join('')}
                    </tr>
                `).join('')}
            </tbody>
        </table>
    </div>
`;

// 任务：计算应考的各班各科平均分
const avgScoreComparison = document.getElementById('avgScoreComparison');

// 计算全校总体平均分
const schoolAvgScores = subjects.map(subject => {
    const total = data.reduce((sum, item) => sum + item[subject], 0);
    return (total / data.length).toFixed(2);
});
const schoolTotalScore = data.reduce((sum, item) => sum + subjects.reduce((s, subject) => s + item[subject], 0), 0);
const schoolAvgTotalScore = (schoolTotalScore / data.length).toFixed(2);

const classAvgScores = classes.map(cls => {
    const classData = data.filter(item => item.班级 === cls);
    const avgScores = subjects.map(subject => {
        const total = classData.reduce((sum, item) => sum + item[subject], 0);
        return (total / classData.length).toFixed(2);
    });
    const totalScore = classData.reduce((sum, item) => sum + subjects.reduce((s, subject) => s + item[subject], 0), 0);
    const avgTotalScore = (totalScore / classData.length).toFixed(2);
    return { class: cls, avgScores, avgTotalScore };
});

// 渲染应考的各班各科平均分为表格
avgScoreComparison.innerHTML = `
    <div class="col-md-12">
        <table class="table table-bordered">
            <thead>
                <tr>
                    <th scope="col">班级</th>
                    ${subjects.map(subject => `<th scope="col">${subject}</th>`).join('')}
                    <th scope="col">总分平均分</th>
                </tr>
            </thead>
            <tbody>
                <!-- 全校总体平均分行 -->
                <tr>
                    <td>全校</td>
                    ${schoolAvgScores.map(score => `<td>${score}</td>`).join('')}
                    <td>${schoolAvgTotalScore}</td>
                </tr>
                ${classAvgScores.map(item => `
                    <tr>
                        <td>${item.class} 班</td>
                        ${item.avgScores.map(score => `<td>${score}</td>`).join('')}
                        <td>${item.avgTotalScore}</td>
                    </tr>
                `).join('')}
            </tbody>
        </table>
    </div>
`;

// 任务：计算实考的各班各科平均分
const actualAvgScore = document.getElementById('actualAvgScore');

// 计算全校实考总体平均分
const schoolActualAvgScores = subjects.map(subject => {
    const attendedData = data.filter(item => item[subject] !== 0);
    const total = attendedData.reduce((sum, item) => sum + item[subject], 0);
    return (total / attendedData.length).toFixed(2);
});

// 计算全校总分平均分，只计算实际参加考试的学生
const schoolAttendedTotalScores = data.filter(item => subjects.some(subject => item[subject] !== 0));
const schoolTotalActualScore = schoolAttendedTotalScores.reduce((sum, item) => sum + subjects.reduce((s, subject) => s + item[subject], 0), 0);
const schoolActualAvgTotalScore = (schoolTotalActualScore / schoolAttendedTotalScores.length).toFixed(2);

const classActualAvgScores = classes.map(cls => {
    const classData = data.filter(item => item.班级 === cls);
    const avgScores = subjects.map(subject => {
        const attendedData = classData.filter(item => item[subject] !== 0);
        const total = attendedData.reduce((sum, item) => sum + item[subject], 0);
        return (total / attendedData.length).toFixed(2);
    });
    // 计算总分平均分，只计算实际参加考试的学生
    const attendedTotalScores = classData.filter(item => subjects.some(subject => item[subject] !== 0));
    const totalScore = attendedTotalScores.reduce((sum, item) => sum + subjects.reduce((s, subject) => s + item[subject], 0), 0);
    const avgTotalScore = (totalScore / attendedTotalScores.length).toFixed(2);
    return { class: cls, avgScores, avgTotalScore };
});

// 渲染实考的各班各科平均分为表格
actualAvgScore.innerHTML = `
    <div class="col-md-12">
        <table class="table table-bordered">
            <thead>
                <tr>
                    <th scope="col">班级</th>
                    ${subjects.map(subject => `<th scope="col">${subject}</th>`).join('')}
                    <th scope="col">总分平均分</th>
                </tr>
            </thead>
            <tbody>
                <!-- 全校实考总体平均分行 -->
                <tr>
                    <td>全校</td>
                    ${schoolActualAvgScores.map(score => `<td>${score}</td>`).join('')}
                    <td>${schoolActualAvgTotalScore}</td>
                </tr>
                ${classActualAvgScores.map(item => `
                    <tr>
                        <td>${item.class} 班</td>
                        ${item.avgScores.map(score => `<td>${score}</td>`).join('')}
                        <td>${item.avgTotalScore}</td>
                    </tr>
                `).join('')}
            </tbody>
        </table>
    </div>
`;

// 任务：计算应考与实考总分平均分和各科平均分差值
const scoreDifference = document.getElementById('scoreDifference');

// 计算全校差值
const schoolDifferences = subjects.map(subject => {
    const total = data.reduce((sum, item) => sum + item[subject], 0);
    const avgScore = total / data.length;
    const attendedData = data.filter(item => item[subject] !== 0);
    const actualAvgScore = attendedData.length > 0 ? attendedData.reduce((sum, item) => sum + item[subject], 0) / attendedData.length : 0;
    return (avgScore - actualAvgScore).toFixed(2);
});

// 计算全校总分差值
const schoolTotalScore5 = data.reduce((sum, item) => sum + subjects.reduce((s, subject) => s + item[subject], 0), 0);
const schoolAvgTotalScore5 = schoolTotalScore5 / data.length;
const schoolActualTotalScore = data.filter(item => subjects.every(subject => item[subject] !== 0))
    .reduce((sum, item) => sum + subjects.reduce((s, subject) => s + item[subject], 0), 0) / 
    data.filter(item => subjects.every(subject => item[subject] !== 0)).length;
const schoolTotalDifference = (schoolAvgTotalScore5 - schoolActualTotalScore).toFixed(2);

const classScoreDifferences = classes.map(cls => {
    const classData = data.filter(item => item.班级 === cls);
    const differences = subjects.map(subject => {
        const total = classData.reduce((sum, item) => sum + item[subject], 0);
        const avgScore = total / classData.length;
        const attendedData = classData.filter(item => item[subject] !== 0);
        const actualAvgScore = attendedData.length > 0 ? attendedData.reduce((sum, item) => sum + item[subject], 0) / attendedData.length : 0;
        return (avgScore - actualAvgScore).toFixed(2);
    });
    const totalScore = classData.reduce((sum, item) => sum + subjects.reduce((s, subject) => s + item[subject], 0), 0);
    const avgTotalScore = totalScore / classData.length;
    const actualTotalScore = classData.filter(item => subjects.every(subject => item[subject] !== 0))
        .reduce((sum, item) => sum + subjects.reduce((s, subject) => s + item[subject], 0), 0) / 
        classData.filter(item => subjects.every(subject => item[subject] !== 0)).length;
    const totalDifference = (avgTotalScore - actualTotalScore).toFixed(2);
    return { class: cls, differences, totalDifference };
});

// 渲染应考与实考总分平均分和各科平均分差值为表格
scoreDifference.innerHTML = `
    <div class="col-md-12">
        <table class="table table-bordered">
            <thead>
                <tr>
                    <th scope="col">班级</th>
                    ${subjects.map(subject => `<th scope="col">${subject}差值</th>`).join('')}
                    <th scope="col">总分平均分差值</th>
                </tr>
            </thead>
            <tbody>
                <!-- 全校差值行 -->
                <tr>
                    <td>全校</td>
                    ${schoolDifferences.map(diff => `<td>${diff}</td>`).join('')}
                    <td>${schoolTotalDifference}</td>
                </tr>
                ${classScoreDifferences.map(item => `
                    <tr>
                        <td>${item.class} 班</td>
                        ${item.differences.map(diff => `<td>${diff}</td>`).join('')}
                        <td>${item.totalDifference}</td>
                    </tr>
                `).join('')}
            </tbody>
        </table>
    </div>
`;

// 任务：计算单科各班最高分
const maxScorePerClass = document.getElementById('maxScorePerClass');

// 计算全校最高分
const schoolMaxScores = subjects.map(subject => {
    const maxScore = Math.max(...data.map(item => item[subject]));
    const studentsWithMaxScore = data.filter(item => item[subject] === maxScore)
        .map(item => `${item.班级}班${item.姓名}`).join(',');
    return { score: maxScore, students: studentsWithMaxScore };
});

// 计算全校总分最高分
const schoolTotalScores = data.map(item => subjects.reduce((sum, subject) => sum + item[subject], 0));
const schoolMaxTotalScore = Math.max(...schoolTotalScores);
const schoolStudentsWithMaxTotalScore = data
    .filter(item => subjects.reduce((sum, subject) => sum + item[subject], 0) === schoolMaxTotalScore)
    .map(item => `${item.班级}班${item.姓名}`).join(', ');

const classMaxScores = classes.map(cls => {
    const classData = data.filter(item => item.班级 === cls);
    const maxScores = subjects.map(subject => {
        const maxScore = Math.max(...classData.map(item => item[subject]));
        const studentsWithMaxScore = classData.filter(item => item[subject] === maxScore).map(item => item.姓名).join(',');
        return { score: maxScore, students: studentsWithMaxScore };
    });
    // 计算总分最高分
    const totalScores = classData.map(item => subjects.reduce((sum, subject) => sum + item[subject], 0));
    const maxTotalScore = Math.max(...totalScores);
    const studentsWithMaxTotalScore = classData.filter(item => subjects.reduce((sum, subject) => sum + item[subject], 0) === maxTotalScore).map(item => item.姓名).join(', ');

    return { class: cls, maxScores, maxTotalScore, studentsWithMaxTotalScore };
});

// 渲染单科各班最高分为表格
maxScorePerClass.innerHTML = `
    <div class="col-md-12">
        <table class="table table-bordered">
            <thead>
                <tr>
                    <th scope="col">班级</th>
                    <th scope="col">总分最高分</th>
                    ${subjects.map(subject => `<th scope="col">${subject}最高分</th>`).join('')}
                </tr>
            </thead>
            <tbody>
                <!-- 全校最高分统计行 -->
                <tr>
                    <td>全校</td>
                    <td>${schoolMaxTotalScore}<br>(${schoolStudentsWithMaxTotalScore})</td>
                    ${schoolMaxScores.map(scoreInfo => `<td>${scoreInfo.score}<br>(${scoreInfo.students})</td>`).join('')}
                </tr>
                ${classMaxScores.map(item => `
                    <tr>
                        <td>${item.class} 班</td>
                        <td>${item.maxTotalScore}<br>(${item.studentsWithMaxTotalScore})</td>
                        ${item.maxScores.map(scoreInfo => `<td>${scoreInfo.score}<br>(${scoreInfo.students})</td>`).join('')}
                    </tr>
                `).join('')}
            </tbody>
        </table>
    </div>
`;

// 计算单科各班第10名的分数
const Rank10ScorePerClass = document.getElementById('Rank10ScorePerClass');

// 计算每个班级在每个学科中的第10名
const classSubjectRank10Scores = classes.map(cls => {
    const classData = data.filter(item => item.班级 === cls);
    const rank10Scores = subjects.map(subject => {
        const sortedData = classData.map(item => ({
            ...item,
            score: item[subject]
        })).sort((a, b) => b.score - a.score);

        // 获取第10名学生的成绩
        const rank10Student = sortedData[9]; // 注意：数组索引从0开始，所以第10名的索引是9

        // 如果班级学生少于10人，rank10Student可能为undefined
        if (!rank10Student) {
            return { subject, rank10Score: null, rank10StudentName: null };
        }

        // 提取第10名学生的成绩
        const rank10Score = rank10Student.score;
        const rank10StudentName = rank10Student.姓名;

        return { subject, rank10Score, rank10StudentName };
    });

    return { class: cls, rank10Scores };
});

// 渲染单科各班第10名的分数为表格
Rank10ScorePerClass.innerHTML = `
    <div class="col-md-12">
        <table class="table table-bordered">
            <thead>
                <tr>
                    <th scope="col">班级</th>
                    ${subjects.map(subject => `<th scope="col">${subject}第10名</th>`).join('')}
                </tr>
            </thead>
            <tbody>
                ${classSubjectRank10Scores.map(item => `
                    <tr>
                        <td>${item.class} 班</td>
                        ${item.rank10Scores.map(scoreInfo => `
                            <td>${scoreInfo.rank10Score ? `${scoreInfo.rank10Score} (${scoreInfo.rank10StudentName})` : '不足10人'}</td>
                        `).join('')}
                    </tr>
                `).join('')}
            </tbody>
        </table>
    </div>
`;

// 计算各班分数段比较
const scoreRangeComparison = document.getElementById('scoreRangeComparison');
const classScoreRanges = classes.map(cls => {
    const classData = data.filter(item => item.班级 === cls);
    const below100 = classData.filter(item => {
        const total = subjects.reduce((sum, subject) => sum + item[subject], 0);
        return total < 100;
    }).length;
    const below200 = classData.filter(item => {
        const total = subjects.reduce((sum, subject) => sum + item[subject], 0);
        return total < 200;
    }).length;
    const above500 = classData.filter(item => {
        const total = subjects.reduce((sum, subject) => sum + item[subject], 0);
        return total > 500;
    }).length;
    const above600 = classData.filter(item => {
        const total = subjects.reduce((sum, subject) => sum + item[subject], 0);
        return total > 600;
    }).length;
    return { class: cls, below100, below200, above500, above600 };
});

// 渲染各班分数段比较为表格
scoreRangeComparison.innerHTML = `
    <div class="col-md-12">
        <table class="table table-bordered">
            <thead>
                <tr>
                    <th scope="col">班级</th>
                    <th scope="col">低于100分人数</th>
                    <th scope="col">低于200分人数</th>
                    <th scope="col">高于500分人数</th>
                    <th scope="col">高于600分人数</th>
                </tr>
            </thead>
            <tbody>
                ${classScoreRanges.map(item => `
                    <tr>
                        <td>${item.class} 班</td>
                        <td>${item.below100} 人</td>
                        <td>${item.below200} 人</td>
                        <td>${item.above500} 人</td>
                        <td>${item.above600} 人</td>
                    </tr>
                `).join('')}
            </tbody>
        </table>
    </div>
`;

// 计算年级各科前100名人数表
const top100PerSubject = document.getElementById('top100PerSubject');
const top100Counts = subjects.map(subject => {
    const sortedData = data.sort((a, b) => b[subject] - a[subject]);
    const top100 = sortedData.slice(0, 100);
    const classCounts = classes.map(cls => {
        return top100.filter(item => item.班级 === cls).length;
    });
    return { subject, classCounts };
});

// 计算总分前100名人数表
const totalScoreTop100 = data.map(item => {
    const totalScore = subjects.reduce((sum, subject) => sum + item[subject], 0);
    return { ...item, totalScore };
}).sort((a, b) => b.totalScore - a.totalScore).slice(0, 100);
const totalScoreClassCounts100 = classes.map(cls => {
    return totalScoreTop100.filter(item => item.班级 === cls).length;
});

// 渲染年级各科前100名人数表为表格（转置后的表格）
top100PerSubject.innerHTML = `
    <div class="col-md-12">
        <table class="table table-bordered">
            <thead>
                <tr>
                    <th scope="col">班级</th>
                    ${subjects.map(subject => `<th scope="col">${subject}</th>`).join('')}
                    <th scope="col">总分</th>
                </tr>
            </thead>
            <tbody>
                ${classes.map((cls, index) => `
                    <tr>
                        <td>${cls}班</td>
                        ${top100Counts.map(item => `<td>${item.classCounts[index]}</td>`).join('')}
                        <td>${totalScoreClassCounts100[index]}</td>
                    </tr>
                `).join('')}
            </tbody>
        </table>
    </div>
`;


// 计算年级各科前200名人数表
const top200PerSubject = document.getElementById('top200PerSubject');
const top200Counts = subjects.map(subject => {
    const sortedData = data.sort((a, b) => b[subject] - a[subject]);
    const top200 = sortedData.slice(0, 200);
    const classCounts = classes.map(cls => {
        return top200.filter(item => item.班级 === cls).length;
    });
    return { subject, classCounts };
});

// 计算总分前200名人数表
const totalScoreTop200 = data.map(item => {
    const totalScore = subjects.reduce((sum, subject) => sum + item[subject], 0);
    return { ...item, totalScore };
}).sort((a, b) => b.totalScore - a.totalScore).slice(0, 200);
const totalScoreClassCounts200 = classes.map(cls => {
    return totalScoreTop200.filter(item => item.班级 === cls).length;
});

// 渲染年级各科前200名人数表为表格（转置后的表格）
top200PerSubject.innerHTML = `
    <div class="col-md-12">
        <table class="table table-bordered">
            <thead>
                <tr>
                    <th scope="col">班级</th>
                    ${subjects.map(subject => `<th scope="col">${subject}</th>`).join('')}
                    <th scope="col">总分</th>
                </tr>
            </thead>
            <tbody>
                ${classes.map((cls, index) => `
                    <tr>
                        <td>${cls}班</td>
                        ${top200Counts.map(item => `<td>${item.classCounts[index]}</td>`).join('')}
                        <td>${totalScoreClassCounts200[index]}</td>
                    </tr>
                `).join('')}
            </tbody>
        </table>
    </div>
`;

// （8）年级各班总分前3名
const topN = 3; //需要班级前多少名在这里改
const top3PerClass = document.getElementById('top3PerClass');
const classTop3Scores = classes.map(cls => {
    const classData = data.filter(item => item.班级 === cls);
    const sortedByTotalScore = classData.map(item => {
        const totalScore = subjects.reduce((sum, subject) => sum + item[subject], 0);
        return { ...item, totalScore };
    }).sort((a, b) => b.totalScore - a.totalScore);

    // 计算班级名次
    let rank = 1;
    let previousScore = -1;
    const top3WithRank = [];
    for (let i = 0; i < sortedByTotalScore.length; i++) {
        if (i > 0 && sortedByTotalScore[i].totalScore < previousScore) {
            rank = i + 1;
        }
        if (rank > topN) {
            break;
        }
        previousScore = sortedByTotalScore[i].totalScore;
        top3WithRank.push({ ...sortedByTotalScore[i], classRank: rank });
    }

    return { class: cls, top3: top3WithRank };
});

// 渲染年级各班总分前3名为表格
top3PerClass.innerHTML = `
    <div class="col-md-12">
        <table class="table table-bordered">
            <thead>
                <tr>
                    <th scope="col">班级</th>
                    <th scope="col">班级名次</th>
                    <th scope="col">姓名</th>
                    <th scope="col">总分</th>
                </tr>
            </thead>
            <tbody>
                ${classTop3Scores.map(item => `
                    ${item.top3.map((student, index) => `
                        <tr>
                            <td>${item.class} 班</td>
                            <td>${student.classRank}</td>
                            <td>${student.姓名}</td>
                            <td>${student.totalScore}</td>
                        </tr>
                    `).join('')}
                `).join('')}
            </tbody>
        </table>
    </div>
`;

// （9）年级总分前20名
const top20AllClass = document.getElementById('top20AllClass');
const sortedByTotalScore = data.map(item => {
    const totalScore = subjects.reduce((sum, subject) => sum + item[subject], 0);
    return { ...item, totalScore };
}).sort((a, b) => b.totalScore - a.totalScore);

// 计算学校名次
let rank = 1;
let previousScore = -1;
const studentsWithRank = sortedByTotalScore.map((student, index) => {
    if (index > 0 && student.totalScore < previousScore) {
        rank = index + 1;
    }
    previousScore = student.totalScore;
    return { ...student, schoolRank: rank };
});

// 确保至少显示20名学生，如果有并列名次则显示更多
const top20Students = [];
let currentRank = 1;
for (let i = 0; i < studentsWithRank.length; i++) {
    if (studentsWithRank[i].schoolRank > 20) {
        break;
    }
    top20Students.push(studentsWithRank[i]);
    currentRank = studentsWithRank[i].schoolRank;
}

// 渲染年级总分前20名为表格
top20AllClass.innerHTML = `
    <div class="col-md-12">
        <table class="table table-bordered">
            <thead>
                <tr>
                    <th scope="col">序号</th>
                    <th scope="col">学校名次</th>
                    <th scope="col">班级</th>
                    <th scope="col">姓名</th>
                    <th scope="col">总分</th>
                </tr>
            </thead>
            <tbody>
                ${top20Students.map((student, index) => `
                    <tr>
                        <td>${index + 1}</td>
                        <td>${student.schoolRank}</td>
                        <td>${student.班级} 班</td>
                        <td>${student.姓名}</td>
                        <td>${student.totalScore}</td>
                    </tr>
                `).join('')}
            </tbody>
        </table>
    </div>
`;

// 计算各班分数段比较（以50分为一个段）
const scoreRange50Comparison = document.getElementById('scoreRange50Comparison');
// 计算最高总分
const maxTotalScore = Math.max(...data.map(item => subjects.reduce((sum, subject) => sum + item[subject], 0)));
// 动态计算 scoreRanges 数组长度，计算总计行
const LevelCnt = Math.ceil(maxTotalScore / 50);
const classScoreRanges50 = classes.map(cls => {
    const classData = data.filter(item => item.班级 === cls);
    const scoreRanges = Array.from({ length: LevelCnt }, (_, i) => 0);

    classData.forEach(student => {
        const totalScore = subjects.reduce((sum, subject) => sum + student[subject], 0);
        const rangeIndex = Math.floor(totalScore / 50);
        scoreRanges[rangeIndex] += 1;
    });

    return { class: cls, scoreRanges };
});

const totalScoreRanges50 = Array.from({ length: LevelCnt }, (_, i) => 0);
data.forEach(student => {
    const totalScore = subjects.reduce((sum, subject) => sum + student[subject], 0);
    const rangeIndex = Math.floor(totalScore / 50);
    totalScoreRanges50[rangeIndex] += 1;
});

// 渲染各班分数段比较为表格
scoreRange50Comparison.innerHTML = `
    <div class="col-md-12">
        <table class="table table-bordered">
            <thead>
                <tr>
                    <th scope="col" style="width: 66px;">班级</th>
                    ${Array.from({ length: LevelCnt }, (_, i) => `<th scope="col">${i * 50}-<br>${(i + 1) * 50 - 0.1}<br>分</th>`).join('')}
                </tr>
            </thead>
            <tbody>
                <!-- 总计行 -->
                <tr>
                    <td>总计</td>
                    ${totalScoreRanges50.map(count => `<td>${count}</td>`).join('')}
                </tr>
                <!-- 各班数据 -->
                ${classScoreRanges50.map(item => `
                    <tr>
                        <td>${item.class} 班</td>
                        ${item.scoreRanges.map(count => `<td>${count}</td>`).join('')}
                    </tr>
                `).join('')}
            </tbody>
        </table>
    </div>
`;

// 计算各学科前3名
const top3PerSubject = document.getElementById('top3PerSubject');
const top3PerSubjectData = subjects.map(subject => {
    const sortedData = data.sort((a, b) => b[subject] - a[subject]);
    const topScores = [];
    let rank = 1;
    for (let i = 0; i < sortedData.length; i++) {
        if (i > 0 && sortedData[i][subject] < sortedData[i - 1][subject]) {
            rank = i + 1;
        }
        if (rank <= 3) {
            topScores.push({ rank, score: sortedData[i][subject], name: sortedData[i].姓名, class: sortedData[i].班级 });
        } else {
            break;
        }
    }
    return { subject, topScores };
});

// 渲染各学科前3名为表格
top3PerSubject.innerHTML = `
    <div class="col-md-12">
        <table class="table table-bordered">
            <thead>
                <tr>
                    <th scope="col">学科</th>
                    <th scope="col">学科名次</th>
                    <th scope="col">分数</th>
                    <th scope="col">姓名</th>
                    <th scope="col">班级</th>
                </tr>
            </thead>
            <tbody>
                ${top3PerSubjectData.map(item => `
                    ${item.topScores.map(student => `
                        <tr>
                            <td>${item.subject}</td>
                            <td>${student.rank}</td>
                            <td>${student.score}</td>
                            <td>${student.name}</td>
                            <td>${student.class} 班</td>
                        </tr>
                    `).join('')}
                `).join('')}
            </tbody>
        </table>
    </div>
`;

// 根据要求，计算各班各科及格人数和及格率、各班各科高分人数和高分率，写入score60PerSubject、score80PerSubject，totalScore为各学科总分

// 第一步：先检测有没有学科及格线和高分线，没有则跳过

if (totalScore !== undefined && totalScore.语文 !== undefined) {
    // 计算各班各科及格人数和及格率、各班各科高分人数和高分率
    const score60PerSubject = document.getElementById('score60PerSubject');
    const score80PerSubject = document.getElementById('score80PerSubject');

    // 定义及格分数和高分分数
    const passScores = {};
    const highScores = {};
    subjects.forEach(subject => {
        passScores[subject] = totalScore[subject] * 0.6;
        highScores[subject] = totalScore[subject] * 0.8;
    });

    // 计算全校及格人数和及格率
    const schoolPassCounts = subjects.map(subject => {
        return data.filter(item => item[subject] >= passScores[subject]).length;
    });
    const schoolHighCounts = subjects.map(subject => {
        return data.filter(item => item[subject] >= highScores[subject]).length;
    });
    const totalStudents = data.length;
    const schoolPassRates = schoolPassCounts.map(count => ((count / totalStudents) * 100).toFixed(2));
    const schoolHighRates = schoolHighCounts.map(count => ((count / totalStudents) * 100).toFixed(2));

    // 计算各班各科的及格人数、及格率、高分人数、高分率
    const classPassRates = classes.map(cls => {
        const classData = data.filter(item => item.班级 === cls);
        const passCounts = subjects.map(subject => {
            return classData.filter(item => item[subject] >= passScores[subject]).length;
        });
        const highCounts = subjects.map(subject => {
            return classData.filter(item => item[subject] >= highScores[subject]).length;
        });
        const totalStudents = classData.length;
        const passRates = passCounts.map(count => ((count / totalStudents) * 100).toFixed(2));
        const highRates = highCounts.map(count => ((count / totalStudents) * 100).toFixed(2));
        return { class: cls, passCounts, passRates, highCounts, highRates };
    });

    // 渲染各班各科及格人数和及格率为表格
    score60PerSubject.innerHTML = `
        <div class="col-md-12">
            <table class="table table-bordered">
                <thead>
                    <tr>
                        <th scope="col">班级</th>
                        ${subjects.map(subject => `<th scope="col">${subject}</th>`).join('')}
                    </tr>
                </thead>
                <tbody>
                    <!-- 全校及格统计行 -->
                    <tr>
                        <td>全校</td>
                        ${schoolPassCounts.map((count, index) => `<td>${count}（${schoolPassRates[index]}%）</td>`).join('')}
                    </tr>
                    ${classPassRates.map(item => `
                        <tr>
                            <td>${item.class} 班</td>
                            ${item.passCounts.map((count, index) => `<td>${count}（${item.passRates[index]}%）</td>`).join('')}
                        </tr>
                    `).join('')}
                </tbody>
            </table>
        </div>
    `;

    // 渲染各班各科高分人数和高分率为表格
    score80PerSubject.innerHTML = `
        <div class="col-md-12">
            <table class="table table-bordered">
                <thead>
                    <tr>
                        <th scope="col">班级</th>
                        ${subjects.map(subject => `<th scope="col">${subject}</th>`).join('')}
                    </tr>
                </thead>
                <tbody>
                    <!-- 全校高分统计行 -->
                    <tr>
                        <td>全校</td>
                        ${schoolHighCounts.map((count, index) => `<td>${count}（${schoolHighRates[index]}%）</td>`).join('')}
                    </tr>
                    ${classPassRates.map(item => `
                        <tr>
                            <td>${item.class} 班</td>
                            ${item.highCounts.map((count, index) => `<td>${count}（${item.highRates[index]}%）</td>`).join('')}
                        </tr>
                    `).join('')}
                </tbody>
            </table>
        </div>
    `;
}

// 偏科学生分析，找出前150名学生中偏科的学生学科成绩
const biasedStudentsAnalysis = document.getElementById('biasedStudentsAnalysis');

// 计算每个科目的排名
const subjectRankings = {};
subjects.forEach(subject => {
    const sortedBySubject = [...data].sort((a, b) => b[subject] - a[subject]);
    subjectRankings[subject] = new Map(
        sortedBySubject.map((student, index) => [
            `${student.班级}-${student.姓名}`,
            index + 1
        ])
    );
});

// 计算总分和总分排名
const studentsWithRanks = data.map(item => {
    const totalScore = subjects.reduce((sum, subject) => sum + item[subject], 0);
    const subjectScores = subjects.map(subject => ({
        subject,
        score: item[subject],
        rank: subjectRankings[subject].get(`${item.班级}-${item.姓名}`)
    }));

    return {
        班级: item.班级,
        姓名: item.姓名,
        totalScore,
        subjectScores
    };
});

// 计算总分排名
const sortedByTotal = [...studentsWithRanks].sort((a, b) => b.totalScore - a.totalScore);
const totalRankMap = new Map(
    sortedByTotal.map((student, index) => [
        `${student.班级}-${student.姓名}`,
        index + 1
    ])
);

// 获取总分前150名的学生
const top150Students = sortedByTotal.slice(0, 150).map(student => {
    const totalRank = totalRankMap.get(`${student.班级}-${student.姓名}`);
    
    // 计算各科排名与总排名的差异
    const rankDeviations = student.subjectScores.map(subject => {
        const rankDiff = subject.rank - totalRank;
        const rankDevPercent = ((rankDiff) / data.length * 100).toFixed(2);
        
        return {
            subject: subject.subject,
            score: subject.score,
            rank: subject.rank,
            rankDiff,
            rankDevPercent: parseFloat(rankDevPercent)
        };
    });

    // 找出偏科科目（排名差异超过总人数的15%的科目）
    const biasedSubjects = rankDeviations.filter(dev => Math.abs(dev.rankDevPercent) > 15);

    return {
        班级: student.班级,
        姓名: student.姓名,
        totalScore: student.totalScore,
        totalRank,
        rankDeviations,
        biasedSubjects
    };
});

// 筛选出有偏科情况的学生
const biasedStudents = top150Students.filter(student => student.biasedSubjects.length > 0);

// 渲染偏科学生分析表格
if(biasedStudentsAnalysis != null)
biasedStudentsAnalysis.innerHTML = `
    <div class="col-md-12">
        <table class="table table-bordered">
            <thead>
                <tr>
                    <th scope="col">总分排名</th>
                    <th scope="col">班级</th>
                    <th scope="col">姓名</th>
                    <th scope="col">总分</th>
                    ${subjects.map(subject => `<th scope="col">${subject}<br>(分数/排名/排名差)</th>`).join('')}
                    <th scope="col">结论</th>
                </tr>
            </thead>
            <tbody>
                ${biasedStudents.map((student) => {
                    // 生成偏科结论
                    const weakSubjects = student.biasedSubjects.filter(s => s.rankDevPercent > 15).map(s => s.subject);
                    const strongSubjects = student.biasedSubjects.filter(s => s.rankDevPercent < -15).map(s => s.subject);
                    const conclusion = [
                        weakSubjects.length > 0 ? `${weakSubjects.join('、')}偏弱` : '',
                        strongSubjects.length > 0 ? `${strongSubjects.join('、')}偏强` : ''
                    ].filter(Boolean).join('，');
                    
                    return `
                    <tr>
                        <td>${student.totalRank}</td>
                        <td>${student.班级}班</td>
                        <td>${student.姓名}</td>
                        <td>${student.totalScore}</td>
                        ${student.rankDeviations.map(dev => {
                            const isDeviated = Math.abs(dev.rankDevPercent) > 15;
                            // 注意：排名差为正表示比总分排名差，所以用红色；为负表示比总分排名好，所以用绿色
                            const deviationClass = dev.rankDevPercent < 0 ? 'text-success' : 'text-danger';
                            return `<td>
                                ${dev.score}<br>
                                ${dev.rank}<br>
                                <span class="${isDeviated ? deviationClass : ''}">
                                    (${dev.rankDevPercent > 0 ? '+' : ''}${dev.rankDevPercent}%)
                                </span>
                            </td>`;
                        }).join('')}
                        <td>${conclusion}</td>
                    </tr>
                `}).join('')}
            </tbody>
        </table>
    </div>
`;